from flask import Blueprint, request, jsonify, send_file
from src.services.report_service import ReportService
import os

reports_bp = Blueprint('reports', __name__)
report_service = ReportService()

@reports_bp.route('/generate', methods=['POST'])
def generate_report():
    """生成报表"""
    try:
        data = request.get_json()
        
        # 验证必要参数
        required_fields = ['template_type', 'task_id']
        for field in required_fields:
            if field not in data:
                return jsonify({'code': 400, 'message': f'缺少必要参数: {field}'}), 400
        
        # 生成报表
        result = report_service.generate_report(
            template_type=data['template_type'],
            task_id=data['task_id'],
            options=data.get('options', {})
        )
        
        return jsonify({
            'code': 200,
            'message': '报表生成成功',
            'data': result
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'生成报表失败: {str(e)}'}), 500

@reports_bp.route('/download/<filename>', methods=['GET'])
def download_report():
    """下载报表"""
    try:
        # 获取报表文件路径
        file_path = report_service.get_report_file_path(filename)
        
        if not os.path.exists(file_path):
            return jsonify({'code': 404, 'message': '文件不存在'}), 404
        
        return send_file(
            file_path,
            as_attachment=True,
            download_name=filename
        )
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'下载失败: {str(e)}'}), 500

@reports_bp.route('/templates', methods=['GET'])
def get_report_templates():
    """获取报表模板列表"""
    try:
        templates = report_service.get_available_templates()
        
        return jsonify({
            'code': 200,
            'message': '查询成功',
            'data': templates
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'查询失败: {str(e)}'}), 500

@reports_bp.route('/list', methods=['GET'])
def get_generated_reports():
    """获取已生成的报表列表"""
    try:
        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('page_size', 20, type=int)
        
        reports = report_service.get_generated_reports(page, page_size)
        
        return jsonify({
            'code': 200,
            'message': '查询成功',
            'data': reports
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'查询失败: {str(e)}'}), 500

@reports_bp.route('/preview/<report_id>', methods=['GET'])
def preview_report():
    """预览报表"""
    try:
        preview_data = report_service.preview_report(report_id)
        
        return jsonify({
            'code': 200,
            'message': '预览成功',
            'data': preview_data
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'预览失败: {str(e)}'}), 500

@reports_bp.route('/status/<task_id>', methods=['GET'])
def get_report_generation_status():
    """获取报表生成状态"""
    try:
        status = report_service.get_generation_status(task_id)
        
        return jsonify({
            'code': 200,
            'message': '查询成功',
            'data': status
        })
        
    except Exception as e:
        return jsonify({'code': 500, 'message': f'查询失败: {str(e)}'}), 500

